from user import models
from rest_framework import serializers
import re


def checkemail(value):
    if not re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', value):
        raise serializers.ValidationError('邮箱格式不正确')
    else:
        emaildata = models.UserModel.objects.filter(email=value)
        if emaildata:
            raise serializers.ValidationError('邮箱已存在')


def checkphone(value):
    if not re.match(r'^1[3-9]\d{9}$', value):
        raise serializers.ValidationError('手机号格式不正确')
    else:
        phonedata = models.UserModel.objects.filter(phone=value)
        if phonedata:
            raise serializers.ValidationError('手机号已存在')


def checkname(value):
    namedata = models.UserModel.objects.filter(username=value)
    if namedata:
        raise serializers.ValidationError('用户名已存在')


class SerUser(serializers.ModelSerializer):
    class Meta:
        model = models.UserModel
        fields = '__all__'
        extra_kwargs = {
            'email': {
                "error_messages": {
                    "unique": "邮箱已存在",
                    "required": "邮箱不能为空"
                },
                'validators': [checkemail]
            },
            'phone': {
                "error_messages": {
                    "unique": "手机号已存在",
                    "required": "手机号不能为空"
                },
                'validators': [checkphone]
            },
            'password': {
                'max_length': 10,
                'min_length': 6,
                'error_messages': {
                    'required': '密码不能为空',
                    'max_length': '密码长度不能超过10位',
                    'min_length': '密码长度不能少于6位'
                }
            },
            'username': {
                'error_messages': {
                    'required': '用户名不能为空',
                    'unique': '用户名已存在'
                }
            },
            'validators': [checkname]
        }


class CouponSer(serializers.ModelSerializer):
    class Meta:
        model = models.CouponModel
        fields = '__all__'


class UserCouponSer(serializers.ModelSerializer):
    coudetail = serializers.SerializerMethodField(read_only=True)

    def get_coudetail(self, obj):
        return {"condition": obj.coupon.condition, "name": obj.coupon.name, "price": obj.coupon.price, "start_time": obj.coupon.created_time,
                "end_time": obj.coupon.end_time}

    class Meta:
        model = models.UserCoupon
        fields = '__all__'
